using System.Collections.Generic;

namespace DependencyAnalysis.Algorithms.SubstringDetection
{
    internal class CommonSubstringStatus
    {
        private readonly int _numberOfTexts;
        public Node Node { get; private set; }
        private bool _allStrings;
        private bool _twoStrings;
        private readonly HashSet<int> _stringSet;
        public int Height { get; private set; }

        public CommonSubstringStatus(Node node, int height, int numberOfTexts)
        {
            _numberOfTexts = numberOfTexts;
            Node = node;
            _stringSet = new HashSet<int>();

            Height = height;
        }

        public bool IsInAtLeastTwoStrings()
        {
            if (!_twoStrings)
            {
                int hits = 0;
                for (int i = 0; i < _numberOfTexts; i++)
                {
                    if (_stringSet.Contains(i))
                    {
                        hits++;
                    }
                    if (hits > 1)
                    {
                        _twoStrings = true;
                        break;
                    }
                }
            }
            return _twoStrings;
        }

        public bool IsInAllStrings()
        {
            if (!_allStrings)
            {
                for (int i = 0; i < _numberOfTexts; i++)
                {
                    if (!_stringSet.Contains(i))
                        return false;
                }
                _allStrings = true;
            }
            return _allStrings;
        }

        public void AddString(int number)
        {
            if (!IsInAllStrings())
            {
                if (!_stringSet.Contains(number))
                    _stringSet.Add(number);
            }
        }

        public void MergeStatus(CommonSubstringStatus status)
        {
            _allStrings |= status._allStrings;
            if (!IsInAllStrings())
            {
                foreach (var i in status._stringSet)
                {
                    _stringSet.Add(i);
                }
            }
        }
    }
}